package com.stars.easyms.demo.service;

import com.stars.easyms.base.util.AopUtil;
import com.stars.easyms.demo.dao.TestDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>className: TestService</p>
 * <p>description: </p>
 *
 * @author
 * @date 2019-05-08 17:46
 */
@Service
public class TestService {

    @Autowired
    private TestDAO testDAO;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insertWithTransaction() {
        testDAO.insertData_test_master();
        // 这里catch住异常，不让当前事务回滚
        try {
            AopUtil.getAopProxy(this).insertWithNestedTransaction1();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 这里catch住异常，不让当前事务回滚
        try {
            AopUtil.getAopProxy(this).insertWithNestedTransaction2();
        } catch (Exception e) {
            e.printStackTrace();
        }
        testDAO.insertData_other2_master();
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
    public void insertWithNestedTransaction1() {
        testDAO.insertData_other1_master();
        testDAO.insertData_test_master();
        testDAO.insertData_other2_master();
    }

    @Transactional(propagation = Propagation.NESTED, rollbackFor = Exception.class)
    public void insertWithNestedTransaction2() {
        testDAO.insertData_other2_master();
        testDAO.insertData_test_master();
        // other1有唯一索引，这里会抛出异常
        testDAO.insertData_other1_master();
    }

}